package com.me.netty.handler;

import com.me.netty.global.ChannelSupervise;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable // 设置通道共享
public class BinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {

    @Override  
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame frame)  {
        ByteBuf content = frame.content();
        ByteBuf byteBuf = Unpooled.directBuffer(content.capacity());
        byteBuf.writeBytes(content);
        // 群发
        ChannelSupervise.send2All(new BinaryWebSocketFrame(byteBuf));
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}